<template>
    <div class="flex-center">
        <el-popover v-if="hover" placement="top" width="150" trigger="hover">
            <div class="code-container flex-center">
                <div class="code-content flex-center">
                    <canvas class="code-img" ref="qrcode"></canvas>
                </div>
            </div>
            <img slot="reference" class="pointer qr-code" src="@/assets/images/qrCode.png" alt="QRCODE" draggable="false" :width="size" />
        </el-popover>

        <canvas v-else class="code-img" ref="qrcode"></canvas>
    </div>
</template>

<script>
import QRCode from 'qrcode';

export default {
    name: 'QRCODE',
    props: {
        size: {
            type: [String, Number],
            default: 15
        },
        params: {
            type: String,
            default: ''
        },
        hover: {
            type: Boolean,
            default: false
        },
        codeSize: {
            type: [String, Number],
            default: 150
        }
    },
    watch: {
        data: {
            handler(nVal) {
                if (nVal) {
                    this.$nextTick(() => {
                        const qrElement = this.$refs.qrcode;

                        const qrData = nVal;

                        const options = { width: this.codeSize, height: this.codeSize, margin: 0 };

                        QRCode.toCanvas(qrElement, qrData, options, (error) => {
                            if (error) {
                                this.$message.error(this.$t('common.error'));
                            }
                        });
                    });
                }
            },
            immediate: true
        }
    }
};
</script>

<style lang="less" scoped>
.qr-code {
    object-fit: contain;
}

.code-container {
    width: 150px;
    height: 150px;

    .code-content {
        width: 150px;
        height: 150px;
    }
}
</style>
